#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <fcntl.h>

#define PORT 6666
#define BUFFER_SIZE 4096
#define SERVER_IP "192.168.142.130"

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int client_fd;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];
    const char *filename = argv[1];

    /* 创建socket */
    if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    /* 配置服务器地址 */
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);

    /* 将IPv4地址从点分十进制转换为二进制形式 */
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0)
    {
        perror("invalid address/ address not supported");
        exit(EXIT_FAILURE);
    }

    /* 连接服务器 */
    if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("connect failed");
        exit(EXIT_FAILURE);
    }

    printf("Connected to server %s:%d\n", SERVER_IP, PORT);

    /* 发送文件名 */
    if (send(client_fd, filename, strlen(filename), 0) == -1)
    {
        perror("send filename failed");
        exit(EXIT_FAILURE);
    }

    /* 打开文件 */
    int file_fd = open(filename, O_RDONLY);
    if (file_fd == -1)
    {
        perror("open file failed");
        exit(EXIT_FAILURE);
    }

    /* 发送文件内容 */
    ssize_t bytes_read;
    while ((bytes_read = read(file_fd, buffer, BUFFER_SIZE)) > 0)
    {
        if (send(client_fd, buffer, bytes_read, 0) == -1)
        {
            perror("send file content failed");
            close(file_fd);
            exit(EXIT_FAILURE);
        }
    }

    close(file_fd);
    close(client_fd);
    printf("File %s sent successfully\n", filename);
    return 0;
}